﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Security.Cryptography;
using System.IO;
using System.Diagnostics;

namespace KillDuplicates {
  public partial class frmMain : Form {

    Dictionary<string, string> dic;

    public frmMain() {
      InitializeComponent();

      
    }

    private void frmMain_Load(object sender, EventArgs e) {
    }

    private string HashMD5(string path) {
      MD5 hash = MD5.Create();
      byte[] res = null;

      using(FileStream x = File.OpenRead(path)) {
        res = hash.ComputeHash(x);
      }

      StringBuilder q = new StringBuilder();
      foreach(byte b in res) {
        q.Append(b.ToString("x2"));
      }
      return q.ToString();
    }

    private void button2_Click(object sender, EventArgs e) {
      
    }

    private void btnBrowse_Click(object sender, EventArgs e) {
      if(fbdFolder.ShowDialog(this) == DialogResult.OK) {
        lbxSearchList.Items.Add(fbdFolder.SelectedPath);
        string[] files = Directory.GetFiles(fbdFolder.SelectedPath, "*.*", SearchOption.AllDirectories);
        tslFileStatus.Text = files.Length.ToString() + " selected";
        listBox1.Items.AddRange(files);
      }
    }

    private void lbxSearchList_KeyDown(object sender, KeyEventArgs e) {
      if(e.KeyCode == Keys.Delete) {
        int index = lbxSearchList.SelectedIndex;
        if(index >= 0) {
          lbxSearchList.Items.RemoveAt(index);
        }
      }
    }

    private void bwSearching_DoWork(object sender, DoWorkEventArgs e) {
      dic = new Dictionary<string, string>();

      for(int i = 0; i < listBox1.Items.Count; ++i) {
        listBox1.SelectedIndex = i;        
        string key = "";
        string fname = "";
        try {
          fname = (string)listBox1.Items[i];
          key = HashMD5(fname);
          dic.Add(key, fname);
        } catch(ArgumentException) {
          TreeNode node = null;
          string original;
          dic.TryGetValue(key, out original);
          int index = treeView1.Nodes.IndexOfKey(original);
          if(index < 0) {
            node = treeView1.Nodes.Add(original, original);
          } else {
            node = treeView1.Nodes[index];
          }
          node.Nodes.Add(fname);
        } catch(IOException) {
          // The file is open byb other process, log the problem
          // and continue.
        } catch {
          // Catch any other exception and do something...
        }
      }
    }
  }
}
